package com.collection;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @classDesc: 功能描述:map的key是list
 * @author: 李明杰
 * @date: 2021/10/27 9:46
 * @copyright 众阳健康
 */
public class MapOfKeyIsList {
    List<String> list1, list2;
    Map<List<String>, String> map;

    @Test
    public void test1() {
        List<String> list1 = new ArrayList<String>();
        list1.add("Elem1");
        list1.add("Elem2");
        Map<List<String>, String> map = new HashMap<List<String>, String>();
        map.put(list1, "Can get value.");
        System.out.println("Elements of list1: " + list1);
        List<String> list2 = new ArrayList<String>();
        list2.add("Elem1");
        list2.add("Elem2");
        System.out.println("Elements of list2: " + list1);
        System.out.println("Test1. Get value from HashMap(Key: list1) by the key list2: " + map.get(list2) + "\n");
    }

    @Test
    public void test2() {
        list1 = new ArrayList<String>();
        list1.add("Elem1");
        map = new HashMap<List<String>, String>();
        map.put(list1, "Can get value.");//list1 only one element, and it's hash code is 67040897
        list1.add("Elem2");//Add one element, even though ArrayList is a kinds of reference type, but map keys' hash code not change.
        System.out.println("Elements of list1: " + list1);
        list2 = new ArrayList<String>();
        list2.add("Elem1");
        list2.add("Elem2");
        System.out.println("Elements of list2: " + list2);
        System.out.println("Test2. Get value from HashMap(Key: list1) by the key list2: " + map.get(list2) + "\n");
    }

    @Test
    public void test3() {
        list1 = new ArrayList<String>();
        list1.add("Elem1");
        map = new HashMap<List<String>, String>();
        map.put(list1, "Can get value.");
        list1.add("Elem2");
        System.out.println("Elements of list1: " + list1);
        Map<List<String>, String> tempMap = new HashMap<List<String>, String>();
        tempMap.putAll(map);//Will be recalculate the keys' hash code
        list2 = new ArrayList<String>();
        list2.add("Elem1");
        list2.add("Elem2");
        System.out.println("Elements of list2: " + list2);
        System.out.println("Test3. Get value from HashMap(Key: list1) by the key list2: " + tempMap.get(list2));
    }
}
